import org.springframework.util.StringUtils;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Test {

    private static ReentrantLock lock = new ReentrantLock();

    private static Condition conA = lock.newCondition();

    private static Condition conB = lock.newCondition();

    private static Condition conC = lock.newCondition();

    private static volatile String flag = "A";


    public static void main(String[] args) {
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                printA();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                printB();
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                printC();
            }
        }, "C").start();
    }

    public static void printA() {
        lock.lock();
        try {
            String name = Thread.currentThread().getName();
            if (!flag.equals("A")) {
                conA.await();
            }
            System.out.println("A");
            flag = "B";
            conB.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void printB() {
        lock.lock();
        try {
            String name = Thread.currentThread().getName();
            if (!flag.equals("B")) {
                conB.await();
            }
            System.out.println("B");
            flag = "C";
            conC.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void printC() {
        lock.lock();
        try {
            String name = Thread.currentThread().getName();
            if (!flag.equals("C")) {
                conC.await();
            }
            System.out.println("C");
            flag = "A";
            conA.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
